$(function() {
	$("#headTop").load("head.html");
	initPersonalMain();

	changeDivWidth();
	initMainHeight();
	// 当浏览器窗口大小改变时，设置显示内容的高度
	window.onresize = function() {
		changeDivWidth();
	}

	$('#west').on('click', '.personal', showPersonalMessage);

	$('#center').on('click', '.edit', editPersonalMsg);

	$('#center').on('blur', '.msg', checkMsg);

	$('#center').on('click', '#updatePsd', updatePassword);

	$('#center').on('blur', '#origin_psd', chenkEditOriginPassword);
	$('#center').on('blur', '#new_psd', chenkEditNewPassword);
	$('#center').on('blur', '#conform_psd', chenkEditConformPassword);
	//重命名标签
	$('#center').on('blur','.rename',renameTag);

	$('#center').on('click', '.personal_tag',showArticleByTag);
	
	$('#center').on('click', '.save_add_tag',saveNewTag);
	
});


function saveNewTag(){
	
	var tagName = $(this).siblings("input").val().trim();
	console.log(tagName);
	if(tagName.length==0){
		$(this).siblings("input").val("");
		return;
	}
	var userId=getCookie("userId");
	var datas={
		'builder':userId,
		'tagNames':tagName
	};
	
	$.ajax({
		url : 'tag/saveTag.do',
		data : datas,
		async : false,
		type : 'post',
		dataType : 'json',
		success : function(result) {
			console.log(result);
			if (result.state == 0) {
				showTags();
			}
		},
		error : function(e) {
			alert("通信失败!");
		}
	});
	
	
	
}

//通过标签获取文章
function showArticleByTag(){
	
	
}

//重命名标签
function renameTag(e){
	
	var tagSpan = $(e.target).parent();
	var tagNewName=e.target.value;
	var tagId = tagSpan[0].title;
	var type="RENAME";
	
	updateTag(tagSpan,tagId,type,tagNewName);
	
}

//更新标签
function updateTag(tagSpan,tagId,type,tagNewName){
	
	var url='tag/updateTag.do';
	var datas={
			"tagId":tagId,
			"tagNewName":tagNewName,
			"type":type
	};
	
	$.post(url,datas,function(result){
		console.log(result);
		if(result.state==0){
			tagSpan.html(tagNewName);
		}
	})
}



function checkMsg() {
	var nickVal = $($(this).children()[0]).val().trim();
	console.log(nickVal);
	var inputName = $(this).children()[0].name;
	var rulePhone = /^1[3|4|5|7|8][0-9]{9}$/;
	var ruleEmail = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/;

	if ("phone" == inputName) {
		if (nickVal == null || nickVal.length == 0 || nickVal == undefined) {
			$(".pensonalDetails").find(".phone").find("input[name='phone']")
					.next('span').html("");
			return true;
		}
		if (rulePhone.test(nickVal)) {
			$(".pensonalDetails").find(".phone").find("input[name='phone']")
					.next('span').html("");
			return true;
		}
		$(".pensonalDetails").find(".phone").find("input[name='phone']").next(
				'span').html(" * 手机号码输入有误");
	}
	if ("email" == inputName) {
		if (nickVal == null || nickVal.length == 0 || nickVal == undefined) {
			$(".pensonalDetails").find(".email").find("input[name='email']")
					.next('span').html("");
			return true;
		}
		if (ruleEmail.test(nickVal)) {
			$(".pensonalDetails").find(".email").find("input[name='email']")
					.next('span').html("");
			return true;
		}
		$(".pensonalDetails").find(".email").find("input[name='email']").next(
				'span').html(" * 邮箱输入有误");
	}
	return false;
}

// 初始化页面高度
function initMainHeight() {
	var h = document.documentElement.clientHeight;// 获取页面可见宽度
	document.getElementById("persponalMain").style.height = h - 53 + "px";
}

// 根据页面改变页面宽度
function changeDivWidth() {
	var w = document.documentElement.clientWidth;// 获取页面可见宽度
	document.getElementById("west").style.width = w * 0.18 + "px";
	document.getElementById("center").style.width = w * 0.58 + "px";
	document.getElementById("east").style.width = w * 0.18 + "px";
}

function initPersonalMain() {
	initCenter();
	initWest();
	initEast();
}

function initCenter() {

}
function initWest() {
	var menu = '<div class="nav">' + '<ul>'
			+ '<li><a class="personal articles">我的文章</a></li>'
			+ '<li><a class="personal details">我的信息</a></li>'
			+ '<li><a class="personal tags">我的标签</a></li>'
			+ '<li><a class="personal collection">我的收藏</a></li>' + '</ul>'
			+ '</div><div class="tagsList"></div>';

	$("#west").html(menu);
	initmenu();
}
function initmenu() {
	var parent, ink, d, x, y;
	$(".nav ul li a").click(function(e) {
		parent = $(this).parent();
		// create .ink element if it doesn't exist
		if (parent.find(".ink").length == 0)
			parent.prepend("<span class='ink'></span>");

		ink = parent.find(".ink");
		// incase of quick double clicks stop the previous animation
		ink.removeClass("animate");

		// set size of .ink
		if (!ink.height() && !ink.width()) {
			// use parent's width or height whichever is larger for the diameter
			// to make a circle which can cover the entire element.
			d = Math.max(parent.outerWidth(), parent.outerHeight());
			ink.css({
				height : d,
				width : d
			});
		}

		// get click coordinates
		// logic = click coordinates relative to page - parent's position
		// relative to page - half of self height/width to make it controllable
		// from the center;
		x = e.pageX - parent.offset().left - ink.width() / 2;
		y = e.pageY - parent.offset().top - ink.height() / 2;

		// set the position and add class .animate
		ink.css({
			top : y + 'px',
			left : x + 'px'
		}).addClass("animate");
	})
}

function initEast() {
	var importBtn = '<a id="importBtn" href="#" class="easyui-linkbutton">我要上传</a>';
	$('#east').html(importBtn);
	$("#importBtn").linkbutton({
		iconCls : 'icon-redo',
		text : '我要上传'
	});

	$('#importBtn').bind('click', importArticle);
}

// 定义目录按钮事件
function showPersonalMessage() {
	$('#center').html("");
	var menu = $(this);
	if (menu.hasClass("details")) {
		showDetails();
	}
	if (menu.hasClass("tags")) {
		console.log("标签");
		showTags();

	}
	if (menu.hasClass("collection")) {
		console.log("收藏");

	}
	if (menu.hasClass("articles")) {
		console.log("文章");

	}
}

// 获取用户创建的tags
function showTags() {

	var tagDiv = '<div class="addTag">'
					+'<input type="text" placeholder="请输入标签 ..."  name="add_tag"></input>'
					+'<input type="button" value="新建标签" name="add_tag" class="save_add_tag"></input>'
				+'</div>'
				+'<div class="tags personal_tags" id="tags" tabindex="1">'
					+ '<div class="tag_zoom">'
//						+ '<input id="form-field-tags" type="text" '
//						+ 'value="Tag Input Control" name="tags" style="display: none;">'
					+'</div>'
				+ '</div>' 
	
	$("#center").html(tagDiv);

	var url = 'tag/getTags.do';
	var data = {
		userId : getCookie('userId')
	};
	$.getJSON(url, data, function(result) {
		if (result.state == 0) {
			showTag(result.data);
		} else {
			alert(result.message);
		}
	});
}



// 显示标签
function showTag(tags) {
	for (var i = 0; i < tags.length; i++) {
		generateTag(tags[i].name, tags[i].id);
	}

	$('.personal_tag').bind('contextmenu',function(e){
		e.preventDefault();
		var tagSpan = $(this);
		var tagName=tagSpan.html();
		$('#tag_menu').menu('show', {
			noline:true,
			left: e.pageX,
			top: e.pageY,
			zIndex:100000000
		});
		$('#tag_menu').menu({    
		    onClick:function(item){   
		    	
		    	var menuId = item.target.id;
		    	if("rename"==menuId){
		    		console.log(menuId);
		    		tagSpan.html("<input type='text' name='rename' class='rename'></input>");
		    		$(".tag_zoom").find('span').find('input').val(tagName);
		    		
		    	}
		    	if("delete"==menuId){
		    		console.log(menuId);
		    		
		    	}		    	
		    }    
		});  
		
	});
}

function showDetails() {
	var userId = getCookie("userId");
	var user = getUserDetails(userId);
	console.log(user);

	var userDetailsDiv = '<div class="pensonalDetails">'
			+ '<div>'
			+ '<p><a class="personal">名称 :</a><a>'
			+ user.name
			+ '</a></p>'
			+ '<p><a class="personal personalMsg">昵称 :</a><a class="nick">'
			+ user.nick
			+ '</a></p>'
			+ '<p><a class="personal personalMsg">电话 :</a><a class="msg phone">'
			+ user.phone
			+ '</a></p>'
			+ '<p><a class="personal personalMsg">邮箱 :</a><a class="msg email">'
			+ user.email
			+ '</a></p>'
			+ '</div>'
			+ '<div id="edit"><a class="edit">编辑</a></div>'
			+ '</div>'
			+ '<div class="password"><div class="update_password"><a id="updatePsd">修改密码</a></div></div>';

	$("#center").html(userDetailsDiv);

}

// 根据标签名称生成标签
function generateTag(tagName, tagId) {
	var tag = tagName.trim();
	if (tag != '') {
		$(".tag_zoom").append(
				"<span class='tag personal_tag' title='" + tagId + "'>" + tag
						+ "</span>"); // 添加标签

	}
};

// 修改密码
function updatePassword() {
	var editPassword = '<div class="edit_password"><table style="border-collapse:separate; border-spacing:10px;">'
			+ '<tr><td align=center>原密码:</td><td><input type="password" class="edit_password_input" name="origin_psd" id="origin_psd"></input><span></span></td></tr>'
			+ '<tr><td align=center>新密码:</td><td><input type="password" class="edit_password_input" name="new_psd" id="new_psd"></input><span></span></td></tr>'
			+ '<tr><td align=center>确认密码:</td><td><input type="password" class="edit_password_input" name="conform_psd" id="conform_psd"></input><span></span></td></tr></table></div>';
	$(this).parent('.update_password').parent('.password').append(editPassword);

	var savePassword = '<div class="save" id="savePsd"><a class="saveBtn" id="savePasswordBtn" href="#" class="easyui-linkbutton">保存</a></div>';

	$(this).parent('.update_password').parent('.password').append(savePassword);

	$("#savePasswordBtn").linkbutton(
			{
				iconCls : 'icon-save',
				text : '保存',
				onClick : function() {
					// 检验界面参数
					var n = chenkEditOriginPassword() + chenkEditNewPassword()
							+ chenkEditConformPassword();
					if (n != 3) {
						return;
					}
					var newPsd = $("#new_psd").val();
					console.log(newPsd);
					updateUser("", "", "", newPsd)
				}
			});

}

// 修改密码-验证密码
function chenkEditOriginPassword() {
	var originPsd = $("#origin_psd").val().trim();
	if (originPsd.length == 0) {
		$('#origin_psd').next('span').html(' * 请输入原密码!');
		return false;
	}
	var userId = getCookie("userId");
	var datas = {
		"userId" : userId,
		"originPsd" : originPsd
	};
	$.ajax({
		url : 'user/checkPsd.do',
		data : datas,
		async : false,
		type : 'post',
		dataType : 'json',
		success : function(result) {
			console.log(result);
			if (result.state == 0) {
				if (result.data == 1) {
					$('#origin_psd').next('span').html("");
				}
				if (result.data == 0) {
					$('#origin_psd').next('span').html(' * 原密码输入错误!');
				}
			}
		},
		error : function(e) {
			alert("通信失败!");
		}
	});
	var spanHtml = $('#origin_psd').next('span').html();
	if (spanHtml.length == 0) {
		return true;
	}
	return false;
}

function chenkEditNewPassword() {
	var pwd = $('#new_psd').val().trim();
	var rule = /^\w{4,16}$/;
	if (rule.test(pwd)) {
		$('#new_psd').next('span').html("");
		return true;
	}
	$('#new_psd').next('span').html(' * 4~16个字符');
	return false;
}

function chenkEditConformPassword() {
	var new_pwd = $('#new_psd').val().trim();
	var conform_pwd = $('#conform_psd').val().trim();
	if (new_pwd.length == 0 || conform_pwd.length == 0) {
		return false;
	}
	if (conform_pwd === new_pwd) {
		$('#conform_psd').next('span').html("");
		return true;
	}
	$('#conform_psd').next('span').html(' * 新密码与确认密码不一致!');
	return false;
}

// 修改个人信息
function editPersonalMsg() {
	var input = $(".pensonalDetails").find(".nick").find('input');

	if (input.length > 0) {
		return;
	}

	var nick = $(".pensonalDetails").find(".nick").text();
	var phone = $(".pensonalDetails").find(".phone").text();
	var email = $(".pensonalDetails").find(".email").text();
	$(".pensonalDetails")
			.find(".nick")
			.html(
					'<input type="text" name="nick" id="user_nick"></input><span></span>');
	$(".pensonalDetails")
			.find(".phone")
			.html(
					'<input type="text" name="phone" id="user_phone"></input><span></span>');
	$(".pensonalDetails")
			.find(".email")
			.html(
					'<input type="text" name="email" id="user_email"></input><span></span>');

	$(".pensonalDetails").find(".nick").find("input[name='nick']").val(nick);
	$(".pensonalDetails").find(".phone").find("input[name='phone']").val(phone);
	$(".pensonalDetails").find(".email").find("input[name='email']").val(email);

	var save = '<div class="save" id="savePersonal"></div>';
	$(".pensonalDetails").append(save);
	var saveBtn = '<a class="saveBtn" id="savePersonalBtn" href="#" class="easyui-linkbutton">保存</a>';
	$("#savePersonal").html(saveBtn);

	$("#savePersonalBtn").linkbutton(
			{
				iconCls : 'icon-save',
				text : '保存',
				onClick : function() {
					var nick = $(".pensonalDetails").find(".nick").find(
							"input[name='nick']").val().trim();
					var phone = $(".pensonalDetails").find(".phone").find(
							"input[name='phone']").val().trim();
					var email = $(".pensonalDetails").find(".email").find(
							"input[name='email']").val().trim();
					updateUser(nick, phone, email);
				}
			});

}

// 更新用户信息
function updateUser(nick, phone, email, password) {
	var userId = getCookie("userId");
	var datas = {
		"userId" : userId,
		"nick" : nick,
		"phone" : phone,
		"email" : email,
		"password" : password
	};
	console.log(datas);
	$.ajax({
		url : 'user/updateUser.do',
		data : datas,
		type : 'post',
		dataType : 'json',
		success : function(result) {
			console.log(result);
			if (result.state == 0) {
				location.href = 'personalCenter.html';
			}
		},
		error : function(e) {
			alert("通信失败!");
		}
	});

}

// 显示编辑框
function importArticle() {
	$('#center').html('');
	$('#importBtn').unbind('click');
	$('#center').load('importArticle.html');
	$("#importBtn").linkbutton({
		iconCls : 'icon-redo',
		text : '上传文章'
	});

	$('#west').html(
			"<div style='margin: 20px 20px'>"
					+ "<ul id='menu' class='easyui-tree'></ul></div>");
}

// 获取不重复字符串
function GenNonDuplicateID(randomLength) {
	return Number(Math.random().toString().substr(3, randomLength) + Date.now())
			.toString(36)
}

// 获取用户详情
function getUserDetails(userId) {
	var user = "";
	var datas = {
		"userId" : userId
	};
	$.ajax({
		url : 'user/getUserDetails.do',
		data : datas,
		async : false,
		type : 'post',
		dataType : 'json',
		success : function(result) {
			if (result.state == 0) {
				user = result.data;
			}
		},
		error : function(e) {
			alert("通信失败!");
		}
	});
	return user;
}
